package com.bookmanagement.controller.admin;

import com.bookmanagement.DTO.BookDTO;
import com.bookmanagement.constant.MessageConstant;
import com.bookmanagement.entity.Book;
import com.bookmanagement.result.Result;
import com.bookmanagement.service.BookService;
import com.bookmanagement.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * 管理端图书管理Controller
 * @author skyjay
 */
@RestController
@RequestMapping("/admin/book")
@Slf4j
public class AdminBookController {

    @Autowired
    private BookService bookService;

    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * 获取所有图书（包括已下架的）
     */
    @GetMapping("/list")
    public Result<List<Book>> getAllBooks() {
        List<Book> books = bookService.getAllBooks();
        return Result.success(books);
    }

    /**
     * 添加图书
     */
    @PostMapping
    public Result addBook(@RequestBody BookDTO bookDTO) {
        bookService.addBook(bookDTO);
        return Result.success();
    }

    /**
     * 更新图书信息
     */
    @PutMapping("/{id}")
    public Result updateBook(@PathVariable("id") Long id, @RequestBody BookDTO bookDTO) {
        bookService.updateBook(id, bookDTO);
        return Result.success();
    }

    /**
     * 删除图书（逻辑删除，将status设置为0）
     */
    @DeleteMapping("/{id}")
    public Result deleteBook(@PathVariable("id") Long id) {
        bookService.deleteBook(id);
        return Result.success();
    }

    /**
     * 上传图书封面
     */
    @PostMapping("/cover")
    public Result<String> uploadCover(MultipartFile file) {
        log.info("上传图书封面：{}", file);
        try {
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = UUID.randomUUID() + extension;
            String coverUrl = aliOssUtil.upload(file.getBytes(), filename);
            return Result.success(coverUrl);
        } catch (IOException e) {
            log.error("封面上传失败：{}", e);
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
}
